package com.b00t.infra;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;

import com.b00t.server.ItemServiceImpl;

import javax.servlet.Filter;
import javax.servlet.http.HttpServlet;
import static com.b00t.infra.StartDevMod.getServerPort;

/**
 * 
 * @author rakesh
 *  
 *  Configure the new service in the main
 *  
 *  
 */
public class StartJetty {
	private final WebAppContext context = new WebAppContext();

	private final int port;
        
	public StartJetty(final int port) {
		this.port = port;
		
		//I need to point war directory
		String currentdir = System.getProperty("user.dir");
		context.setResourceBase(currentdir+"/"+"war");
		context.setContextPath("/");
		context.setWelcomeFiles(new String[] { "B00t.html" });
	}

	public Server getServer() {
		Server server = new Server(port);
		server.setHandler(context);
		return server;
	}

	public StartJetty addFilter(Class<? extends Filter> type, String path) {
		context.addFilter(type, path, FilterMapping.DEFAULT);
		return this;
	}

	public StartJetty addFilter(Filter filter, String path) {
		context.addFilter(new FilterHolder(filter), path, FilterMapping.DEFAULT);
		return this;
	}

	public void startAndJoin() throws Exception {
		final Server server = getServer();
		server.start();
		server.join();
	}

	public StartJetty addServlet(final Class<? extends HttpServlet> servletClass,final String pathSpec) {
		context.addServlet(servletClass, pathSpec);
		return this;
	}

	public StartJetty addServlet(final HttpServlet httpServlet,	final String pathSpec) {
		context.addServlet(new ServletHolder(httpServlet), pathSpec);
		return this;
	}
	
	public static void main(String[] arg){
		try {
			System.out.println("Starting Jetty on:" + getServerPort());
			new StartJetty(getServerPort()).addServlet(ItemServiceImpl.class, "/b00t/item").startAndJoin();
			System.out.println("Started jetty on" + getServerPort());
		} catch (Exception e) {
			System.out.println("Jetty can not be started");
		}
	}

}
